<template>
  <div class="fulltable">
    <div class="full">
      <div class="add" v-if="isSuperman">  
        <button class="button" @click="showAddUserDialog">➕新增</button>  
      </div>  
      <div class="search-box">  
        <el-input v-model="searchQuery" placeholder="搜索真实姓名" style="width:200px;margin-right: 10px;"  @keyup.enter="search" clearable></el-input>  
      </div>  
    <el-table
    :data="filteredData.slice((currentPage - 1) * pageSize, currentPage * pageSize)"  
    :height="tableHeight"
    border
    style="width: 100%">
    <el-table-column
      prop="realname"
      label="真实姓名"
      width="180">
    </el-table-column>
    <el-table-column
      prop="deptname"
      label="部门"
      width="180">
    </el-table-column>
     <el-table-column
      prop="position"
      label="职位"
      width="180">
    </el-table-column>
      <el-table-column
      prop="tel"
      label="电话"
      width="180">
    </el-table-column>
        <el-table-column label="操作">  
          <template slot-scope="scope">  
            <el-button type="primary" size="small" @click="viewItem(scope.row)">详情</el-button>  
            <el-button type="warning" size="small" v-if="isSuperman" @click="editItem(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" v-if="isSuperman" @click="deleteItem(scope.row)">删除</el-button>  
          </template>  
        </el-table-column> 
    </el-table>
      <div class="paging">
      <el-pagination  
        @size-change="handleSizeChange"  
        @current-change="handleCurrentChange"  
        :current-page="currentPage"  
        :page-sizes="[5,10, 20, 40, 60]"  
        :page-size="pageSize"  
        :pager-count="4"  
        layout="total, sizes, prev, pager, next, jumper"  
        :total="filteredData.length">  <!-- 使用 filteredData.length -->  
      </el-pagination>  
      </div>
  </div>
<el-dialog title="新增用户" :visible.sync="showAddDialog" width="60%">  
  <el-form :model="newUser" :rules="rules" ref="newUserForm" label-width="80px">  

    <el-row>  
      <el-col :span="12">  
        <el-form-item label="部门" prop="deptname">  
          <el-select v-model="newUser.deptname" filterable placeholder="请选择部门">  
            <el-option v-for="item in deptList" :key="item.id" :label="item.deptname" :value="item.id"></el-option>  
          </el-select>  
        </el-form-item>  
      </el-col>  
    </el-row>  

    <el-row>  
      <el-col :span="12">  
        <el-form-item label="真实姓名" prop="realname">  
          <el-input v-model="newUser.realname"></el-input>  
        </el-form-item>  
      </el-col>  
      <el-col :span="12">  
        <el-form-item label="性别" prop="gender">  
          <el-select v-model="newUser.gender" placeholder="请选择性别">  
            <el-option v-for="genderitem in genderOptions" :key="genderitem.value" :label="genderitem.label" :value="genderitem.value"></el-option>  
          </el-select>  
        </el-form-item>  
      </el-col>  
    </el-row>  

    <el-row>  
      <el-col :span="12">  
        <el-form-item label="账号" prop="account">  
          <el-input v-model="newUser.account"></el-input>  
        </el-form-item>  
      </el-col>  
      <el-col :span="12">  
        <el-form-item label="电话" prop="tel">  
          <el-input v-model="newUser.tel"></el-input>  
        </el-form-item>  
      </el-col>  
    </el-row>  

    <el-row>  
      <el-col :span="12">  
        <el-form-item label="职位" prop="position">  
          <el-select v-model="newUser.position" filterable placeholder="请选择职位">  
            <el-option v-for="positionitem in optionList" :key="positionitem.id" :label="positionitem.position" :value="positionitem.id"></el-option>  
          </el-select>  
        </el-form-item>   
      </el-col>  
      <el-col :span="12">  
          <el-form-item label="直属上级" prop="superior">  
            <el-select v-model="newUser.superior" placeholder="请选择直属上级">  
              <el-option  
                v-for="user in userData"  
                :key="user.id"  
                :label="user.realname"  
                :value="user.id">  
              </el-option>  
            </el-select>  
          </el-form-item>  
        </el-col> 
    </el-row>  

    <el-row>  
      <el-col :span="12">  
        <el-form-item label="角色" prop="role">  
          <el-select v-model="newUser.role" placeholder="请选择角色">  
            <el-option v-for="roleItem in roleOptions" :key="roleItem.value" :label="roleItem.label" :value="roleItem.value"></el-option>  
          </el-select>  
        </el-form-item>  
      </el-col>  
        <el-col :span="12">  
        <el-form-item label="入职时间" prop="joinDate">  
          <el-date-picker v-model="newUser.joinDate" type="date" placeholder="选择入职时间"></el-date-picker>  
        </el-form-item>  
      </el-col>  
    </el-row>  

    <el-row>  
      <el-col :span="12">  
        <el-form-item label="人员类型" prop="employeeType">  
          <el-select v-model="newUser.employeeType" placeholder="请选择人员类型">  
            <el-option label="正式" value="1"></el-option>  
            <el-option label="外包" value="2"></el-option>  
            <el-option label="实习" value="3"></el-option>  
          </el-select>  
        </el-form-item>  
      </el-col>  

    </el-row>  

  </el-form>  
  <div slot="footer" class="dialog-footer">  
    <el-button @click="showAddDialog = false; newUser = {};">取 消</el-button>  
    <el-button type="primary" @click="saveNewUser">确 定</el-button>  
  </div>  
</el-dialog>
  <el-dialog  
      title="用户详情"  
      :visible.sync="detailDialogVisible"  
      width="50%">  
      <el-tabs v-model="activeTab">  
        <el-tab-pane label="基本详情" name="basic">  
          <el-form :model="selectedUser" label-width="80px">  
            <el-form-item label="真实姓名">  
              <el-input v-model="selectedUser.realname" disabled></el-input>  
            </el-form-item>  
            <el-form-item label="性别">  
              <el-input v-model="selectedUser.gender" disabled></el-input>  
            </el-form-item>  
            <el-form-item label="用户id">  
              <el-input v-model="selectedUser.autoid" disabled></el-input>  
            </el-form-item> 

            <el-form-item label="电话">  
              <el-input v-model="selectedUser.tel" disabled></el-input>  
            </el-form-item>   
            <el-form-item label="生日">  
              <el-input v-model="selectedUser.birth" disabled></el-input>  
            </el-form-item> 
            <el-form-item label="银行卡号">  
              <el-input v-model="selectedUser.bankcard" disabled></el-input>  
            </el-form-item>  
          </el-form>  
        </el-tab-pane>  
        <el-tab-pane label="工作详情" name="work">  
          <el-form :model="selectedUser" label-width="80px">  
            <el-form-item label="部门">  
              <el-input v-model="selectedUser.deptname" disabled></el-input>  
            </el-form-item>  
            <el-form-item label="职位">  
              <el-input v-model="selectedUser.position" disabled></el-input>  
            </el-form-item>  
            <el-form-item label="角色">  
              <el-input v-model="selectedUser.role" disabled></el-input>  
            </el-form-item>  
            <el-form-item label="直属上级">  
              <el-input v-model="selectedUser.superior" disabled></el-input>  
            </el-form-item>  
            <el-form-item label="人员类型">  
              <el-input v-model="selectedUser.employeeType" disabled></el-input>  
            </el-form-item>  
            <el-form-item label="入职时间">  
              <el-input v-model="selectedUser.joinDate" disabled></el-input>  
            </el-form-item>  
          </el-form>  
        </el-tab-pane>  
      </el-tabs>  
      <div slot="footer" class="dialog-footer">  
        <el-button @click="detailDialogVisible = false">取 消</el-button>  
      </div>  
    </el-dialog>
    <el-dialog title="编辑用户" :visible.sync="editDialogVisible" width="30%">  
      <el-form :model="editUser"  ref="editUserForm" label-width="80px">  
        <el-row>  
          <el-col :span="24">  
            <el-form-item label="部门" prop="deptname">  
              <div style="display: flex; align-items: center;">
                <el-select v-model="editUser.deptname" filterable placeholder="请选择部门" style="width: 207px">  
                  <el-option v-for="item in deptList" :key="item.id" :label="item.deptname" :value="item.id"></el-option>  
                </el-select>
                <span style="margin-left: 10px; color: #409EFF;">当前: {{ currentInfo.deptname || '无' }}</span>
              </div>  
            </el-form-item>  
          </el-col>  
        </el-row>  

        <el-row>  
          <el-col :span="24">  
            <el-form-item label="真实姓名" prop="realname">  
              <el-input v-model="editUser.realname" style="width: 207px!important;"></el-input>  
            </el-form-item>  
          </el-col>  
        </el-row>  

        <el-row>  
          <el-col :span="24">  
            <el-form-item label="性别" prop="gender">  
              <el-select v-model="editUser.gender" placeholder="请选择性别">  
                <el-option v-for="genderitem in genderOptions" :key="genderitem.value" :label="genderitem.label" :value="genderitem.value"></el-option>  
              </el-select>  
            </el-form-item>  
          </el-col>  
        </el-row>  
        <el-row>  
          <el-col :span="24">  
            <el-form-item label="职位" prop="position">  
              <div style="display: flex; align-items: center;">
                <el-select v-model="editUser.position" filterable placeholder="请选择职位" style="width: 207px">  
                  <el-option v-for="positionitem in optionList" :key="positionitem.id" :label="positionitem.position" :value="positionitem.id"></el-option>  
                </el-select>
                <span style="margin-left: 10px; color: #409EFF;">当前: {{ currentInfo.position || '无' }}</span>
              </div>  
            </el-form-item>   
          </el-col>  
        </el-row>  

        <el-row>  
          <el-col :span="24">  
            <el-form-item label="电话" prop="tel">  
              <el-input v-model="editUser.tel" style="width: 207px!important;"></el-input>  
            </el-form-item>  
          </el-col>  
        </el-row>  

        <el-row>  
          <el-col :span="24">  
            <el-form-item label="角色" prop="role">  
              <div style="display: flex; align-items: center;">
                <el-select v-model="editUser.role" placeholder="为空则变为普通员工" style="width: 207px">  
                  <el-option v-for="roleItem in roleOptions" :key="roleItem.value" :label="roleItem.label" :value="roleItem.value" ></el-option>  
                </el-select>
                <span style="margin-left: 10px; color: #409EFF;">当前: {{ getRoleName(currentInfo.role) || '无' }}</span>
              </div>  
            </el-form-item>  
          </el-col>  
        </el-row>

        <el-row>  
          <el-col :span="24">  
            <el-form-item label="直属上级" prop="superior">  
              <div style="display: flex; align-items: center;">
                <el-select v-model="editUser.superior" placeholder="请选择直属上级" style="width: 207px">  
                  <el-option v-for="user in userData" :key="user.id" :label="user.realname" :value="user.id"></el-option>  
                </el-select>
                <span style="margin-left: 10px; color: #409EFF;">当前: {{ currentInfo.superior || '无' }}</span>
              </div>  
            </el-form-item>  
          </el-col>   
        </el-row>  

        <el-row>  
          <el-col :span="24">  
            <el-form-item label="人员类型" prop="employeeType">  
              <div style="display: flex; align-items: center;">
                <el-select v-model="editUser.employeeType" placeholder="请选择人员类型" style="width: 207px">  
                  <el-option label="正式" value="1"></el-option>  
                  <el-option label="外包" value="2"></el-option>  
                  <el-option label="实习" value="3"></el-option>  
                </el-select>
                <span style="margin-left: 10px; color: #409EFF;">当前: {{ getEmployeeTypeName(currentInfo.employeeType) || '无' }}</span>
              </div>  
            </el-form-item>  
          </el-col>  
        </el-row>  

        <el-row>  
          <el-col :span="12">  
            <el-form-item label="入职时间" prop="joinDate">  
              <el-date-picker v-model="editUser.joinDate" type="date" placeholder="选择入职时间"></el-date-picker>  
            </el-form-item>  
          </el-col>  
        </el-row>  
      </el-form>  
      <div slot="footer" class="dialog-footer">  
        <el-button type="danger" @click="resetPassword(editUser.id)">重置密码</el-button>
        <el-button type="primary" @click="saveEditUser">确 定</el-button>  
        <el-button @click="editDialogVisible = false">取 消</el-button>  


      </div>  
    </el-dialog>
  </div>
</template>

<script>
import {getUserList,addUser,deleteUserById,getUserDetialById,updateUser,updateUserPassword} from '@/api/user';
import {getDeptList} from '@/api/dept';
import {getOptionList} from '@/api/option';
import { jwtDecode } from 'jwt-decode'; 
import {addLog} from '@/api/log';
export default {
  data(){
    return {
      userData:[],
        currentPage: 1,  
        pageSize: 5  ,
        tableHeight: 350,  
        maxTableHeight: 700, // 最大高度 600px  
        minTableHeight: 350,
        showAddDialog: false, // 是否显示新增对话框  
        detailDialogVisible: false, // 控制查看详情对话框的显示  
        selectedUser: {}, // 存储选中的用户信息
        searchQuery: '',  // 用于存储搜索输入 
        logItem:{
              mn:'',
              opn:'',
              res:''
      },
      newUser: {   
        deptname: '',  
        username: '',  
        realname: '',   
        gender: '',   
        position: '',   
        account: '',  
        password: '',   
        tel: '',  
        role: '', // 新增角色字段  
        superior: '', // 新增直属上级字段  
        employeeType: '', // 新增人员类型字段  
        joinDate: '', // 新增入职时间字段  
        country: '', // 新增工作国家字段  
        city: '', // 新增工作城市字段 
        birth:'',
        bankcard:'',
        autoid:'',
      },  
        isSuperman: this.checkUserRole(), // 检查用户角色并设置  
        genderOptions: [  
          { label: '男', value: '男' },  
          { label: '女', value: '女' }  
        ] ,
        rules: { // 表单验证规则  
           
          username: [  
            { required: true, message: '请输入用户名', trigger: 'blur' }  
          ],  
          realname: [  
            { required: true, message: '请输入真实姓名', trigger: 'blur' }  
          ],  
          gender: [  
              { required: true, message: '请选择性别', trigger: 'change' }  
            ] ,
          account: [  
            { required: true, message: '请输入账号', trigger: 'blur' }  
          ],  
          password: [  
            { required: true, message: '请输入密码', trigger: 'blur' }  
          ],  
          position: [  
            { required: true, message: '请输入职位', trigger: 'blur' }  
          ],  
          tel: [  
            { required: true, message: '请输入电话', trigger: 'blur' },  
            { pattern: /^1\d{10}$/, message: '请输入正确的手机号码', trigger: 'blur' }  
          ],
          role: [  // 新增角色字段的规则  
            { required: true, message: '请选择角色', trigger: 'change' }  
          ],  
          superior: [  
            { required: true, message: '请选择直属上级', trigger: 'change' }  
          ] ,
          employeeType: [  // 新增人员类型字段的规则  
            { required: true, message: '请选择人员类型', trigger: 'change' }  
          ],  
          joinDate: [  // 新增入职时间字段的规则  
            { required: true, message: '请选择入职时间', trigger: 'change' }  
          ]    
        },
        deptList:[],
        optionList:[],
        roleOptions: [  
          { label: '超级管理员', value: '1' },  
          { label: '普通用户', value: '0' },
          { label: '普通管理员',value:'2'},  
          // 添加其他角色选项  
        ],
        editDialogVisible: false,
        editUser: {
          id: '',
          deptname: '',
          realname: '',
          gender: '',
          position: '',
          tel: '',
          role: '',
          superior: '',
          employeeType: '',
          joinDate: ''
        },
        currentInfo: {}, // 存储当前编辑用户的原始信息
    }
  },
  computed: {  
  filteredData() {  
    if (!this.searchQuery) {  
      return this.userData;  // 如果没有搜索关键词，返回全部数据  
    }  
    return this.userData.filter(item =>  
      item.realname.toLowerCase().includes(this.searchQuery.toLowerCase())  // 根据真实姓名过滤  
    );  
  }  
},
  created(){
    getUserList().then(response=>{
      this.userData = response.data
      this.calculateTableHeight() 
      console.log(response.data)
    }).catch(error =>{
      console.log(error)
      this.tableHeight = this.minTableHeight 
    })
    this.getOptions();
    this.getDepts();
  },
watch: {  
  currentPage() {  
    this.calculateTableHeight();  
  },  
  pageSize() {  
    this.calculateTableHeight();  
  },  
  searchQuery() {  // 监听 searchQuery 的变化  
    this.currentPage = 1;  // 重置当前页为 1  
    this.calculateTableHeight();  // 重新计算表格高度  
  }  
},  
  methods:{
    handleSizeChange(val) {  
      this.pageSize = val;  
      this.currentPage = 1;  
      this.logItem.mn = "handleSizeChange";
      this.logItem.opn = "改变每页显示的人员数量";
      this.logItem.res = "true";
      addLog(this.logItem);
    },  
    handleCurrentChange(val) {  
      this.currentPage = val;  
      this.logItem.mn = "handleCurrentChange";
      this.logItem.opn = "改变页码-人员管理";
      this.logItem.res = "true";
      addLog(this.logItem);
    },  
calculateTableHeight() {  
  const currentPageData = this.filteredData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);  
  let height = (currentPageData.length + 1) * 60;  // 每行60px  
  this.tableHeight = Math.max(this.minTableHeight, Math.min(height, this.maxTableHeight));  
},
checkUserRole() {  
    const token = localStorage.getItem('token'); // 从本地存储获取 token  
    if (token) {  
      const decodedToken = jwtDecode(token); // 解码 token  
      return decodedToken.role === 'SUPERMAN'; // 检查角色  
    }  
    return false; // 无 token 返回 false  
  }, 
  showAddUserDialog() {  
    this.showAddDialog = true  
  }, 
  saveNewUser() {  
    this.$refs.newUserForm.validate((valid) => {  
      if (valid) {  
        // 调用接口保存新用户  
        addUser(this.newUser).then(response => {  
          
          console.log('保存新增职位:', this.newUser);   
          this.logItem.mn = "saveNewUser";
          this.logItem.opn = "新增用户";
          this.logItem.res = "true";
          addLog(this.logItem);
          //刷新页面
          window.location.reload()  
          //关闭对话框
          this.showAddDialog = false;  
          this.newUser = [];
          this.$message.success('新用户添加成功')  
        }).catch(error => {  
          console.error(error)  
          this.logItem.mn = "saveNewUser";
          this.logItem.opn = "新增用户";
          this.logItem.res = "false";
          addLog(this.logItem);
          this.$message.error('新用户添加失败')  
        })  
      } else {  
        return false  
      }  
    })  
  },
  getOptions(){
      getOptionList().then((response) => {  
        console.log("职位信息")
        console.log(response.data)
        this.optionList = response.data;  
      });  
  },
  getDepts(){
      getDeptList().then((response) => {  
        console.log(response.data)
        this.deptList = response.data;  
      });  
  },
  deleteItem(row) {  
  this.$confirm('确定要删除此用户吗?', '警告', {  
    confirmButtonText: '确定',  
    cancelButtonText: '取消',  
    type: 'warning'  
  }).then(() => {  
    // 调用删除 API  
    deleteUserById(row.id).then(response => {  
      // 从 userData 中移除已删除的项  
      console.log(row)
      this.userData = this.userData.filter(item => item.id !== row.id);  
      this.$message.success('用户删除成功');  
      this.logItem.mn = "deleteItem";
      this.logItem.opn = "删除用户";
      this.logItem.res = "true";
      addLog(this.logItem);
      window.location.reload()  
    }).catch(error => {  
      console.error(error);  
      this.logItem.mn = "deleteItem";
      this.logItem.opn = "删除用户";
      this.logItem.res = "false";
      addLog(this.logItem);
      this.$message.error('用户删除失败');  
    });  
  }).catch(() => {  
    this.$message.info('已取消删除');  
  });  
},
viewItem(row) {  
  getUserDetialById(row.id).then((response)=>{
  this.detailDialogVisible = true; // 打开查看详情对话框  
  console.log(response.data)
  this.selectedUser = response.data
  this.activeTab = 'basic'; // 默认展示基础详情 
  this.logItem.mn = "viewItem";
  this.logItem.opn = "查看用户详情";
  this.logItem.res = "true";
  addLog(this.logItem);
  })
},
editItem(row) {
  // 获取用户详细信息并打开编辑弹窗
  getUserDetialById(row.id).then((response) => {
    // 保存当前信息用于显示
    this.currentInfo = {
      deptname: response.data.deptname,
      position: response.data.position,
      role: response.data.role,
      superior: response.data.superior,
      employeeType: response.data.employeeType
    };

    // 清空编辑表单的值
    this.editUser = {
      id: response.data.id,
      deptname: '',
      realname: response.data.realname,
      gender: response.data.gender,
      position: '',
      tel: response.data.tel,
      role: '',
      superior: '',
      employeeType: '',
      joinDate: response.data.joinDate
    };
    
    this.editDialogVisible = true;
  }).catch(error => {
    console.error('获取用户详情失败:', error);
    this.$message.error('获取用户详情失败');
  });
},
saveEditUser() {
  this.$refs.editUserForm.validate((valid) => {
    if (valid) {
      updateUser(this.editUser).then(response => {
        this.$message.success('用户信息更新成功');
        this.editDialogVisible = false;
        this.logItem.mn = "saveEditUser";
        this.logItem.opn = "编辑用户信息";
        this.logItem.res = "true";
        addLog(this.logItem);
        // 刷新页面
        window.location.reload();
      }).catch(error => {
        console.error('更新失败:', error);
        this.logItem.mn = "saveEditUser";
        this.logItem.opn = "编辑用户信息";
        this.logItem.res = "false";
        addLog(this.logItem);
        this.$message.error('用户信息更新失败');
      });
    } else {
      return false;
    }
  });
},
// 获取角色名称
getRoleName(role) {
  const roleMap = {
    '0': '普通用户',
    '1': '超级管理员',
    '2': '普通管理员'
  };
  return roleMap[role] || role;
},

// 获取人员类型名称
getEmployeeTypeName(type) {
  const typeMap = {
    '1': '正式',
    '2': '外包',
    '3': '实习'
  };
  return typeMap[type] || type;
},
resetPassword(userId) {
  this.$confirm('确定要重置该用户的密码吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 调用重置密码的 API
    updateUserPassword(userId) // 假设使用默认密码
      .then(response => {
        this.$message.success('密码重置成功');
        this.logItem.mn = "resetPassword";
        this.logItem.opn = "重置用户密码";
        this.logItem.res = "true";
        addLog(this.logItem);
      })
      .catch(error => {
        console.error('重置密码失败:', error);
        this.$message.error('密码重置失败');
        this.logItem.mn = "resetPassword";
        this.logItem.opn = "重置用户密码";
        this.logItem.res = "false";
        addLog(this.logItem);
      });
  }).catch(() => {
    this.$message.info('已取消重置密码');
  });
},
  } 
}
</script>

<style lang="less" scoped>
.fulltable{
  margin-top: 20px;
  height: 700px;
}
.full{
  height: 800px;
  margin: 0;
  padding: 0;
  background: pink;
  padding-top:10px;
  margin-left: 20px;
  margin-right: 20px;
  border-radius: 10px;
  flex: 1;
}
.add{
  padding: 10px;
}
/deep/.el-table .cell {  
  color: black;
}  
.button{
  background: #788fd3;
  color: white;
}
.paging{
  margin: 0;
  padding: 0;
  padding-top:10px;
  margin-left: 20px;
  margin-right: 20px;
  border-radius: 10px;
  flex: 1;

  /deep/ .el-pagination {
    display: flex;  
    justify-content: flex-end;  
  }
}

.el-form-item {
  /deep/ .el-form-item__content {
    display: flex;
    align-items: center;
  }
}

.current-value {
  margin-left: 10px;
  color: #409EFF;
  font-size: 14px;
}
</style>